<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<head><%--领料出库--%>
    <link rel="stylesheet" href="${APP_PATH}/static/layui/css/layui.css" type="text/css"/>
    <style type="text/css">
        td .layui-form-select{
            margin-top: -5px;
        }
        /*设置 layui 表格中单元格内容溢出可见样式*/
        #divtable .layui-table-view,
        #divtable .layui-table-box,
        #divtable .layui-table-body{
            overflow: visible;
            padding: 0 0 0 0;
            margin: 0 0 0 0; /* 根据实际情况调整 */
        }
        #divtable .layui-table-cell{height: auto; overflow: visible;}
    </style>
</head>
<div id="yclMaterialOut" style="margin: 30px">
    <%--query tools--%>
        <blockquote class="layui-elem-quote">
            <form class="layui-form" id="materialBackForm">
                <div class="layui-fluid">
                    <div class="layui-row">
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">领料编号</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" v-model="queryParams.applycode" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">生产厂</label>
                                <div class="layui-input-inline">
                                    <select id="materialAreaCodeSelect" lay-filter="materialAreaCodeSelect" lay-search>
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">子库</label>
                                <div class="layui-input-inline">
                                    <select id="warehouse" lay-filter="warehouse" lay-search>
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal"
                                        @click="queryPageView">
                                    <i class="layui-icon">&#xe615;</i>查询
                                </button>
                            </div>
                            <div class="layui-inline">
                                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm"
                                        @click="restQueryParams">
                                    <i class="layui-icon">&#xe669;</i>重置
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">物料编号</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" v-model="queryParams.materialCode" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">机台</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" v-model="queryParams.device" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">班次</label>
                                <div class="layui-input-inline">
                                    <select id="shiftcode" lay-filter="shiftcode" lay-search>
                                        <option value="">请选择</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-row">
                        <div class="layui-col-sm3">
                            <div class="layui-inline">
                                <label style="width: 65px">配送单号</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" v-model="queryParams.deliveryId" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </blockquote>
    <%-- table grid --%>
    <div id="divtable">
        <table id="tableGridPickOutsourcing" lay-filter="tableGridFilterPickOutsourcing"></table>
    </div>
    <%-- table grid toolbar --%>
    <script type="text/html" id="tableGridToolbarOutsourcing">
        <div class="layui-btn-container">
            <label class="layui-word-aux">领料申请单</label>
        </div>
        <div class="layui-btn-container" id="pick_btn">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="printDelivery">
                <i class="layui-icon">&#xe66d;</i>打印配送单
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="addIn">
                <i class="layui-icon">&#xe654;</i>增行
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" lay-event="save">
                <i class="layui-icon">&#xe605;</i>出库
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">
                <i class="layui-icon">&#xe640;</i>清除
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" lay-event="backOrder">
                <i class="layui-icon">&#xe640;</i>回退
            </button>
        </div>
    </script>
    <%-- table grid toolbar --%>
    <iframe style="visibility:hidden;" id="iframeMove" src="/wms/ycl/production/picking/toPrint" width=0 height=0> </iframe>
</div>

<script src="/wms/static/js/techbloom/LodopFuncs.js" charset="utf-8"></script>
<script>

    const context_path = '${APP_PATH}';
    const table = layui.table,
        form = layui.form,
        layer = layui.layer,
        laydate = layui.laydate;
    let tableGridIns;
    let tableGridIns3;

    //获取table的list集合
    let vm = new Vue({
        el: '#yclMaterialOut',
        data: {
            tableList: [],
            areaList: [], // 厂区
            warhouseList: [],
            queryParams: { //查询参数
                warehouse: "",
                areaCode: "",
                item_code: "",
                device: "",
                shiftcode: "",
                fac_name: "",
                applycode: "",
                deliveryId: ""
            }
        },
        methods: {
            initTableIns() {
                // 订单物料
                tableGridIns = table.render({
                    elem: '#tableGridPickOutsourcing'
                    //, url: context_path + '/ycl/production/picking/list'
                    , data: []
                    , page: false
                    , toolbar: '#tableGridToolbarOutsourcing'
                    , id: "tableGridPickOutsourcing"
                    , size: 'sm'
                    , where: vm.queryParams
                    , limit: 99999
                    , load:false
                    , multiSelect: false
                    , text: {
                        none: '请选择生产厂与子库进行查询！' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                    }
                    , defaultToolbar: []
                    , cols: [[
                        {type: 'checkbox'}
                        , {field: 'tempId', title: '', hide: true}
                        , {field: 'moCode', title: '领料单号', width: 160}
                        , {field: 'lineNum', title: '行号', width: 40}
                        , {field: 'itemCode', title: '物料编码', width: 100}
                        , {field: 'itemDesc', title: '物料名称', style:'overflow:hidden', width: 150}
                        , {field: 'facName', title: '生产厂', width: 100}
                        , {field: 'shiftCode', title: '班次', width: 60}
                        , {field: 'deviceName', title: '机台', style:'overflow:hidden', width: 120}
                        , {field: 'quantity', title: '领料数量', width: 60}
                        , {field: 'storeQuantity', title: '库存数量', width: 60}
                        , {field: 'outQuantity', title: '出库数量', width: 60, edit: 'text'}
                        , {field: 'boxAmount', title: '件数', width: 60, edit: 'text'}
                        , {field: 'lotsNum', title: '批次号', width: 125, templet: (d)=>vm.renderSelectOptions(d)}
                        , {field: 'locatorCode', title: '库位编码', width: 60}
                        , {field: 'primaryUomCode', title: '单位', width: 60}
                        , {field: 'fromSubinvDesc', title: '来源子库', style:'overflow:hidden', width: 90}
                        , {field: 'deliveryId', title: '配送单号', style:'overflow:hidden'}
                        //, {field: 'facName', title: '领料生产厂', width: 105}
                        // , {field: 'opName', title: '工序', width: 105}
                        // , {field: 'userName', title: '申请人', width: 80}
                        // , {field: 'needByDate', title: '申请日期'}
                    ]]
                });
            },
            renderSelectOptions: function(e){
                var list = [];
                $.ajax({
                    type: 'GET',
                    url: context_path + '/ycl/production/picking/lotsnum/' + e.organizationId + '/' + vm.queryParams.warehouse + '/' + e.itemCode,
                    async: false,
                    dataType: "json",
                    success: function (res) {
                        list = res.data;
                    }
                });

                var html = [];
                html.push('<div class="layui-form" lay-filter="lotsNum">');
                html.push('<select name="lotsNum" id="lotsNum" data-value="'+e.tempId+'" lay-filter="lotsNum" lay-search="">');
                html.push('<option value="">请选择</option>');

                if(list) {
                    list.forEach(m => {
                        html.push('<option value="');
                        html.push(m.CODE);
                        html.push('"');

                        if (m.LOTS_NUM == e.lotsNum) {
                            html.push(' selected="selected"');
                        }
                        html.push('>');
                        html.push(m.TEXT);
                        html.push('</option>');
                    })
                }
                html.push('</select></div>');
                return html.join('');
            },
            //第二栏
            resetSelect(data, settings) {
                let html = '';
                let list = data;
                for (let i = 0; i < list.length; i++) {
                    html += '<option value=' + list[i].code + '>' + list[i].text + '</option>';
                }
                let $id = $('#' + settings);
                $id.empty();
                $id.append('<option value="">请选择</option>');
                $id.append(html);
                form.render('select');
            },
            resetSelect1(data, settings) {
                let html = '';
                let list = data;
                for (let i = 0; i < list.length; i++) {
                    html += '<option value=' + list[i].id + '>' + list[i].name + '</option>';
                }
                let $id = $('#' + settings);
                $id.empty();
                $id.append('<option value="">请选择</option>');
                $id.append(html);
                form.render('select');
            },
            resetSelect2(data, settings) {
                let html = '';
                let list = data;
                for (let i = 0; i < list.length; i++) {
                    html += '<option value=' + list[i] + '>' + list[i] + '</option>';
                }
                let $id = $('#' + settings);
                $id.empty();
                $id.append('<option value="">请选择</option>');
                $id.append(html);
                form.render('select');
            },
            initSelect(url, data, domId, callback) {
                let dataJson = { queryString: "", pageSize: 15, pageNo: 1 };
                let json = $.extend({}, dataJson, data);
                $.ajax({
                    type: 'GET',
                    url: context_path + url,
                    data: json,
                    async: false,
                    dataType: "json",
                    success: function (res) {
                        let html = '';
                        let list = res.data;
                        callback(list);
                        for (let i = 0; i < list.length; i++) {
                            html += '<option value=' + list[i].code + '>' + list[i].text + '</option>';
                        }
                        $("#" + domId).append(html);
                        form.render('select');
                    }
                });
            },
            initSelect1(url, data, domId, callback) {
                let dataJson = { queryString: "", pageSize: 15, pageNo: 1 };
                let json = $.extend({}, dataJson, data);
                $.get(context_path + url, json, function (res) {
                    let html = '';
                    let list = res.rows;
                    callback(list);
                    for (let i = 0; i < list.length; i++) {
                        html += '<option value=' + list[i].code + '>' + list[i].text + '</option>';
                    }
                    $("#" + domId).append(html);
                    form.render('select');
                })
            },
            initSelect2(url, data, domId, callback) {
                let dataJson = { queryString: "", pageSize: 15, pageNo: 1 };
                let json = $.extend({}, dataJson, data);
                $.post(context_path + url, json, function (res) {
                    let html = '';
                    let list = res.result;
                    callback(list);
                    for (let i = 0; i < list.length; i++) {
                        html += '<option value=' + list[i] + '>' + list[i] + '</option>';
                    }
                    $("#" + domId).append(html);
                    form.render('select');
                })
            },
            initAreaList() {
                this.initSelect('/ycl/baseinfo/basedata/plant/82', {}, 'materialAreaCodeSelect', (list) => vm.areaList = list);
            },
            //仓库
            initWareHouseList() {
                this.initSelect('/ycl/baseinfo/basedata/store/0', {}, 'warehouse', (list) => vm.warhouseList = list);
            },
            //仓库
            initShiftCodeList() {
                this.initSelect2('/ycl/baseinfo/factorymachine/selectShiftCode', {}, 'shiftcode', (list) => vm.shiftcodeList = list);
            },
            /*查询*/
            queryPageView() {
                if(vm.queryParams.warehouse == ''){
                    layer.alert('请选择子库进行查询');
                    return;
                }
                table.reload('tableGridPickOutsourcing', {
                    url: context_path + '/ycl/production/picking/list',
                    where: vm.queryParams
                });
            },
            /*重置*/
            restQueryParams() {
                vm.queryParams = {
                    warehouse: "",
                    item_code: "",
                    areaCode: "",
                    device: "",
                    shiftcode: "",
                    fac_name: "",
                    applycode: "",
                    materialCode: "",
                    deliveryId: ""
                };
                this.resetSelect(vm.areaList, 'materialAreaCodeSelect');
                this.resetSelect(vm.warhouseList, 'warehouse');
                this.resetSelect2(vm.shiftcodeList, 'shiftcode');
                this.queryPageView();
            },
            printMoveOrder(){
                var selectData = layui.table.checkStatus('tableGridPickOutsourcing').data;

                if (selectData.length != 1)
                {
                    layer.alert('请选中一条记录操作!');
                    return;
                }
                var frm =document.getElementById('iframeMove');
                frm.src = context_path + '/ycl/production/picking/toPrint?moCode='+selectData[0].moCode;
                $(frm).load(function(){
                    LODOP=getLodop();
                    var strHtml=frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(0,0,"100%","100%",strHtml);
                    LODOP.PREVIEW();
                });
            },
        },
        created() {},
        mounted() {}
    })

    /*针对第二栏按钮请求*/
    table.on('toolbar(tableGridFilterPickOutsourcing)', function (obj) {
        const checkStatusData = table.checkStatus(obj.config.id).data
        let oldData = table.cache['tableGridPickOutsourcing'];
        switch (obj.event) {
            case 'printDelivery':
                var selectData = layui.table.checkStatus('tableGridPickOutsourcing').data;

                if (selectData.length == 0) {
                    layer.alert('请选中记录操作!');
                    return;
                }

                let temp_mo_code = '';
                let mo_codes = '';
                let org_code = selectData[0].orgCode;
                let delivery_id = selectData[0].deliveryId;
                for(var i = 0; i < selectData.length; i++){
                    if(temp_mo_code == selectData[i].moCode){
                        continue;
                    }
                    if(delivery_id != selectData[i].deliveryId){
                        layer.alert('选择行中含有已生成的配送单，无法再次生成');
                        return;
                    }

                    temp_mo_code = selectData[i].moCode;
                    delivery_id = selectData[i].deliveryId;
                    mo_codes += selectData[i].moCode + ',';
                }

                mo_codes = mo_codes.substring(0, mo_codes.length - 1);

                let url = "";

                if(delivery_id){
                    url = context_path + "/ycl/production/picking/toPrintDv?deliveryId=" + delivery_id;
                } else {
                    url = context_path + "/ycl/production/picking/toPrintDv?moCode=" + mo_codes;
                }

                var frm =document.getElementById('iframeMove');
                frm.src = url;
                $(frm).load(function(){
                    LODOP=getLodop();
                    var strHtml=frm.contentWindow.document.documentElement.innerHTML;
                    LODOP.ADD_PRINT_HTM(2,0,"100%","100%",strHtml);
                    LODOP.PREVIEW();
                });


                break;
            case 'addIn':
                if(checkStatusData.length == 0){
                    layer.msg('请选择一条数据', {icon: 2});
                    return
                }
                if(checkStatusData.length > 1){
                    layer.msg('只能选择一条数据', {icon: 2});
                    return
                }
                let new_data = [];

                for(var i = 0; i < oldData.length; i++){
                    new_data.push(oldData[i]);
                    if(oldData[i].LAY_CHECKED){
                        checkStatusData[0].tempId = new Date().valueOf();
                        new_data.push(checkStatusData[0]);
                    }
                }

                table.reload('tableGridPickOutsourcing', {
                    url: '',
                    data: new_data
                })
                break;
            case 'save' :

                if(checkStatusData.length == 0){
                    layer.msg('请选择要出库的数据', {icon: 2});
                    return;
                }

                let total_quantity = checkStatusData[0].storeQuantity;

                var add_quantity = 0;
                var line_num = checkStatusData[0].lineNum;
                for(var i = 0; i < checkStatusData.length; i++){
                    if(line_num != checkStatusData[i].lineNum){
                        if (total_quantity < add_quantity) {
                            layer.msg('同一行号出库数量的和不能超过库存数量', {icon: 2});
                            return
                        }
                        add_quantity = 0;
                        total_quantity = checkStatusData[i].storeQuantity;
                    }
                    if(!checkStatusData[i].lotsNum){
                        layer.msg("请填写第" + (i + 1) + "行的批次号", {icon: 2});
                        return;
                    }
                    if(!checkStatusData[i].outQuantity){
                        layer.msg("请填写第" + (i + 1) + "行的出库数量", {icon: 2});
                        return;
                    }
                    // if(!checkStatusData[i].package){
                    //     layer.msg("请填写第" + (i + 1) + "行的件数", {icon: 2});
                    //     return;
                    // }
                    if(!checkStatusData[i].locatorCode){
                        layer.msg("请填写第" + (i + 1) + "行的库位编码", {icon: 2});
                        return;
                    }
                    var outQuantity = checkStatusData[i].outQuantity == ''?0:checkStatusData[i].outQuantity;
                    add_quantity += outQuantity*1;

                    line_num = checkStatusData[i].lineNum;

                    if(i == checkStatusData.length -1){
                        if (total_quantity < add_quantity) {
                            layer.msg('同一行号出库数量的和不能超过库存数量', {icon: 2});
                            return
                        }
                    }
                }

                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/production/picking/save",
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(checkStatusData),
                    success: function (res) {
                        if (res.result === false) {
                            layer.msg(res.msg, {icon: 5});
                            return false;
                        } else {
                            layer.msg(res.msg, {icon: 1});
                            tableGridIns.reload();
                        }
                    }
                })

                break;
            case 'delete' :

                for (let data of checkStatusData) {
                    for (let i = 0; i < oldData.length; i++) {
                        if (oldData[i].tempId === data.tempId) {
                            oldData.splice(i, 1);
                            break;
                        }
                    }
                }
                table.reload('tableGridPickOutsourcing', {
                    url: '',
                    data: oldData
                })

                break;
            case 'backOrder' :
                var selectData = layui.table.checkStatus('tableGridPickOutsourcing').data;

                if (selectData.length == 0) {
                    layer.alert('请选中记录操作!');
                    return;
                }

                let temp_line_id = '';
                let line_ids = '';
                for(var i = 0; i < selectData.length; i++){
                    if(temp_line_id == selectData[i].lineId){
                        continue;
                    }

                    temp_line_id = selectData[i].lineId;
                    line_ids += selectData[i].lineId + ',';
                }

                line_ids = line_ids.substring(0, line_ids.length - 1);

                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/production/picking/deleteorder?line_ids=" + line_ids,
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    success: function (res) {
                        if (res.result === false) {
                            layer.msg(res.msg, {icon: 5});
                            return false;
                        } else {
                            layer.msg(res.msg, {icon: 1});

                            let lineids = line_ids.split(',');
                            for (let data of lineids) {
                                console.log(data);
                                for (let i = 0; i < oldData.length; i++) {
                                    if (data == oldData[i].lineId) {
                                        oldData.splice(i, 1);
                                    }
                                }

                            }

                            table.reload('tableGridPickOutsourcing', {
                                url: '',
                                data: oldData
                            })
                        }
                    }
                })

                break;
        }
    });

    // 监听编辑单元格
    table.on('edit(tableGridFilterPickOutsourcing)', function (obj) { //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
        console.log(obj.value); //得到修改后的值
        console.log(obj.field); //当前编辑的字段名
        console.log(obj.data); //所在行的所有相关数据
    });

    // 点击订单物料
    // table.on('row(tableGridFilterPickOutsourcing)', function (obj) {
    //     const data = obj.data;
    //
    //     let oldData = table.cache['tableGridPickOutsourcing'];
    //     console.log(oldData.length);
    //     if(oldData.length > 0){
    //         var oldlineid = oldData[0].moCode;
    //
    //         if(data.moCode != oldlineid) {
    //             layer.confirm("是否清空列表重新录入?", function () {
    //                 layer.closeAll();
    //                 tableGridIns3.reload({
    //                     url: context_path + '/ycl/production/picking/outlist',
    //                     where: {
    //                         moCode: data.moCode,
    //                         outstats: vm.queryParams.outstats
    //                     }
    //                 })
    //             },function(){
    //                 return false;
    //             })
    //         }
    //     } else {
    //
    //         tableGridIns3.reload({
    //             url: context_path + '/ycl/production/picking/outlist',
    //             where: {
    //                 moCode: data.moCode,
    //                 outstats: vm.queryParams.outstats
    //             }
    //         })
    //     }
    //
    //     //标注选中样式
    //     obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    // });

    //监听select
    form.on('select(materialAreaCodeSelect)', function (data) {
        vm.queryParams.areaCode = data.value;
    });

    //监听select
    form.on('select(warehouse)', function (data) {
        vm.queryParams.warehouse = data.value;
    });

    //监听select
    form.on('select(shiftcode)', function (data) {
        vm.queryParams.shiftcode = data.value;
    });

    //监听select
    form.on('select(lotsNum)', function (data) {
        var elem = data.othis.parents('tr');
        var id = elem.first().find('td').eq(1).text();
        var tbData = table.cache['tableGridPickOutsourcing'];
        var temp = data.value.split(',');
        tbData.forEach(n=>{
            if (n.tempId==id)
            {
                n.lotsNum = temp[0];
                n.locatorCode = temp[1];
                n.storeQuantity = temp[2];
            }
        })
        table.reload('tableGridPickOutsourcing', {
            url: '',
            data: tbData
        })
    });

    // init
    ;!function () {
        vm.initAreaList();
        vm.initWareHouseList();
        vm.initShiftCodeList();
        vm.initTableIns();
    }();
</script>
